package thread.lockAndCondition;


import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 阻塞队列
 * Created by 4790K_NSL on 2017/4/25.
 */
public class BoundedBuffer {

    private int putptr,takeprt,count;

    private Object[] items=new Object[100];

    private Lock lock=new ReentrantLock();

    private Condition notEmpty=lock.newCondition();

    private Condition notFull=lock.newCondition();

    public void put(Object o) throws InterruptedException {
        lock.lock();
        try {
            while(count==items.length){
                notFull.await();
            }
            items[putptr]=o;
            if(++putptr==items.length){
                putptr=0;
            }
            count++;
            notEmpty.signal();
        }finally {
            lock.unlock();
        }
    }

    public Object take() throws InterruptedException {
        Object resutl=null;
        lock.lock();
        try {
            resutl=items[takeprt];
            while(count==0){
                notEmpty.await();
            }
            if(++takeprt==items.length){
                takeprt=0;
            }
            count--;
            notFull.signal();
        }finally {
            lock.unlock();
        }
        return resutl;
    }
}
